//
//  SWBookPhotoEditorViewController.swift
//  YiyaPuzzleDemo
//
//  Created by linhan on 16/9/28.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
import UIKit

protocol SWBookPhotoEditorViewControllerDelegate:NSObjectProtocol
{
    func photoEditorViewControllerProcessComplete(_ viewController:SWBookPhotoEditorViewController, image:UIImage, imageID:String)
}

protocol SWIMainCanvas:class
{
    var image:UIImage?{get set}
    var pluginCanvas:UIView?{get set}
    var size:CGSize{get}
}

class SWBookPhotoEditorViewController: SWBaseViewController,SWImageCropperDelegate,SWEditorExpandToolbarDelegate,ImagePickerHelperDelegate
{
    var imageID:String
    var bookID:String?
    weak var delegate:SWBookPhotoEditorViewControllerDelegate?
    
    private let BackgroundColor = UIColor(hex: 0x232222)
    private var _change:Bool = false
    private var _image:UIImage?
    private var _cropper:SWImageCropper = SWImageCropper()
    
    private var _originData:Data?
    private var _originImage:UIImage?
    
    private var _mainToolbar:UIView = UIView()
    private var _expandToolbar:SWEditorExpandToolbar?
    
    private var _imagePicker:ImagePickerHelper?
    
    init(imageID:String)
    {
        self.imageID = imageID
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit
    {
        print("DEINIT SWBookPhotoEditorViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override func viewWillLayoutFirstTime() {
        
    }
    
    private func setup()
    {
        view.backgroundColor = BackgroundColor
        
        let topToolbarHeight:CGFloat = 80
        let topToolbar:UIView = UIView()
        topToolbar.backgroundColor = BackgroundColor
        topToolbar.frame = CGRectMake(0, 0, view.width, topToolbarHeight)
        view.addSubview(topToolbar)
        
        _imagePicker = ImagePickerHelper()
        _imagePicker?.delegate = self
        _imagePicker?.containerViewController = self
        _imagePicker?.cropSize = CGSizeZero
        
        _cropper.delegate = self
        _cropper.frame = CGRectMake(0, topToolbar.bottom, view.width, view.width)
        _cropper.contentInsets = UIEdgeInsetsMake(10, 10, 10, 10)
        view.addSubview(_cropper)
        
        
        let bottomToolbarHeight:CGFloat = 50
        let bottomToolbar:UIView = UIView()
        bottomToolbar.backgroundColor = BackgroundColor
        bottomToolbar.frame = CGRectMake(0, view.height - bottomToolbarHeight, view.width, bottomToolbarHeight)
        view.addSubview(bottomToolbar)
        _mainToolbar = bottomToolbar
        
        
        let cancelBtn:UIButton = UIButton(type: .custom)
        cancelBtn.setImage(UIImage(named:"editor_icon_cancel"), for: .normal)
        cancelBtn.sizeToTouchEasy()
        cancelBtn.center = CGPointMake(cancelBtn.width * 0.5, bottomToolbar.height * 0.5)
        cancelBtn.addTarget(self, action: #selector(cancelBtnTapped), for: .touchUpInside)
        bottomToolbar.addSubview(cancelBtn)
        
        let confirmBtn:UIButton = UIButton(type: .custom)
        confirmBtn.setImage(UIImage(named:"editor_icon_ok"), for: .normal)
        confirmBtn.sizeToTouchEasy()
        confirmBtn.center = CGPointMake(view.width - confirmBtn.width, bottomToolbar.height * 0.5)
        confirmBtn.addTarget(self, action: #selector(confirmBtnTapped(_:)), for: .touchUpInside)
        bottomToolbar.addSubview(confirmBtn)
        
        
        let resetBtn:UIButton = UIButton(type: .system)
        resetBtn.setTitle("原图", for: .normal)
        resetBtn.sizeToTouchEasy()
        resetBtn.frame = CGRectMake(40, 0, resetBtn.width, resetBtn.height)
        resetBtn.addTarget(self, action: #selector(resetBtnTapped), for: .touchUpInside)
        bottomToolbar.addSubview(resetBtn)
        
        let effectBtn:UIButton = UIButton(type: .system)
        effectBtn.setTitle("滤镜", for: .normal)
        effectBtn.sizeToTouchEasy()
        effectBtn.frame = CGRectMake(80, 0, effectBtn.width, effectBtn.height)
        effectBtn.addTarget(self, action: #selector(effectBtnTapped), for: .touchUpInside)
        bottomToolbar.addSubview(effectBtn)
        
        let flipBtn:UIButton = UIButton(type: .system)
        flipBtn.setTitle("翻转", for: .normal)
        flipBtn.sizeToTouchEasy()
        flipBtn.frame = CGRectMake(120, 0, flipBtn.width, flipBtn.height)
        flipBtn.addTarget(self, action: #selector(flipBtnTapped), for: .touchUpInside)
        bottomToolbar.addSubview(flipBtn)
        
        let rotationBtn:UIButton = UIButton(type: .system)
        rotationBtn.setTitle("旋转", for: .normal)
        rotationBtn.sizeToTouchEasy()
        rotationBtn.frame = CGRectMake(160, 0, rotationBtn.width, rotationBtn.height)
        rotationBtn.addTarget(self, action: #selector(rotationBtnTapped), for: .touchUpInside)
        bottomToolbar.addSubview(rotationBtn)
        
        let replaceBtn:UIButton = UIButton(type: .system)
        replaceBtn.setTitle("换图", for: .normal)
        replaceBtn.sizeToTouchEasy()
        replaceBtn.frame = CGRectMake(200, 0, replaceBtn.width, replaceBtn.height)
        replaceBtn.addTarget(self, action: #selector(replaceBtnTapped), for: .touchUpInside)
        bottomToolbar.addSubview(replaceBtn)
        
        
        SWBookAssetManager.sharedManager().ioQueue.async {
            let manager = SWBookAssetManager.sharedManager()
            //初次使用用原图，编辑过后用编辑后的图
            let modified = manager.imageModified(self.imageID)
            if modified
            {
                self._image = manager.getImage(self.imageID, level: .processed) ?? manager.getImage(self.imageID, level: .origin)
            }
            else
            {
                self._image = manager.getImage(self.imageID, level: .origin) ?? manager.getImage(self.imageID, level: .processed)
            }
            DispatchQueue.main.async(execute: {
                self._cropper.image = self._image
            })
        }
    }
    
    func imageCropperDidEndDragging(_ cropper:SWImageCropper)
    {
        _change = true
    }
    
    func imageCropperDidEndZooming(_ cropper:SWImageCropper)
    {
        _change = true
    }
    
    private func close()
    {
        dismiss(animated: true, completion: nil)
    }
    
    private func showExpandToolbar(_ toolbar:SWEditorExpandToolbar)
    {
        toolbar.canvas = _cropper
        toolbar.image = _image
        toolbar.toolbarWillAppear(true)
        toolbar.y = view.height
        view.addSubview(toolbar)
        
        _expandToolbar = toolbar
        
        UIView.animate(withDuration:0.3, animations: {
            toolbar.y = self.view.height - toolbar.height
            self._mainToolbar.y = self.view.height
            },completion:{finish in
                toolbar.toolbarDidAppear(true)
        })
    }
    
    private func hideExpandToolbar()
    {
        if let toolbar = _expandToolbar
        {
            toolbar.toolbarWillDisappear(true)
            UIView.animate(withDuration: 0.3, animations: {
                toolbar.y = self.view.height
                },completion:{finish in
                    toolbar.toolbarDidDisappear(true)
                    toolbar.removeFromSuperview()
                    self._expandToolbar = nil
            })
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            self._mainToolbar.y = self.view.height - self._mainToolbar.height
        })
    }
    
    
    //取消
    func expandToolbarCancel()
    {
        hideExpandToolbar()
    }
    
    //确定
    func expandToolbarConfirmed(_ image:UIImage)
    {
        hideExpandToolbar()
        _change = true
        _image = image
        _cropper.image = image
    }
    
    //MARK ================================= ImagePickerHelperDelegate =========================
    func imagePickerDidFinishPickingImage(image:UIImage?)
    {
        guard let image = image else{
            return
        }
        _change = true
        _originImage = image
        _image = image
        
        DispatchQueue.main.async(execute: {
            self._cropper.image = self._image
        })
    }
    
    //原图
    @objc private func resetBtnTapped()
    {
        SWBookAssetManager.sharedManager().ioQueue.async {
            if let image = SWBookAssetManager.sharedManager().getImage(self.imageID, level: .origin)
            {
                self._change = true
                self._image = image
                DispatchQueue.main.async(execute: {
                    self._cropper.image = self._image
                })
            }
        }
    }
    
    @objc private func effectBtnTapped()
    {
        let toolbar = SWEditorEffectToolbar(frame: CGRectMake(0, 0, view.width, 100))
        toolbar.backgroundColor = BackgroundColor
        toolbar.optimizationSize = CGSizeMake(view.width, view.height).multiply(UIScreen.main.scale)
        toolbar.delegate = self
        showExpandToolbar(toolbar)
    }
    
    @objc private func flipBtnTapped()
    {
        _change = true
        if let image = _image
        {
            let aImage = ImageUtil.flipHorizontal(image)
            _cropper.image = aImage
            _image = aImage
        }
    }
    
    @objc private func rotationBtnTapped()
    {
        _change = true
        if let image = _image
        {
            let aImage = ImageUtil.rotate(image, angle: 90)
            _cropper.image = aImage
            _image = aImage
        }
    }
    
    @objc private func replaceBtnTapped()
    {
        _imagePicker?.presentPhotoLibraryPickerController(allowsEditing: false)
    }
    
    @objc private func cancelBtnTapped()
    {
        close()
    }
    
    @objc private func confirmBtnTapped(_ button:UIButton)
    {
        let cropRect = _cropper.cropRect
        if let image = _image, !cropRect.isEmpty && _change
        {
            SVProgressHUD.show(withStatus: "保存中...")
            button.isEnabled = false
            DispatchQueue.global(priority: .default).async{
                let processedImage = Toucan.Util.croppedImageWithRect(image, rect: cropRect)
                
                let saveCompletion = {
                    self.delegate?.photoEditorViewControllerProcessComplete(self, image:processedImage, imageID: self.imageID)
                    DispatchQueue.main.async{
                        button.isEnabled = true
                        SVProgressHUD.dismiss()
                        self.close()
                    }//end main_queue
                }
                
                if let originImage = self._originImage
                {
                    SWBookAssetManager.sharedManager().replacePhoto(self.imageID, processedImage: processedImage, originImage: originImage, originData: nil, completion: saveCompletion)
                }
                else
                {
                    SWBookAssetManager.sharedManager().updatePhoto(processedImage, imageID: self.imageID, completion: saveCompletion)
                }
                
                
            }//end global_queue
        }
        else
        {
            close()
        }
    }
    
    
}
